<?php

namespace app\api\model\cps;

use app\api\model\ExtendConsume;
use app\api\model\UserConsumeLog;
use app\api\model\UserOverlordMealOrder;
use app\shopapi\model\ExtendConsumeShop;
use fast\Http;
use think\Log;

class MtMeal
{

    //public $ceshiurl = 'https://offsiteact.st.meituan.com/';

    public $url = 'https://offsiteact.meituan.com/';

    public $p = 'd6bdd852a11e481292e4298c0a939157';

    public $mediaPvid = '47e6b65d2a51d2c93d4cd359c953e886';

    const VIPARA = 'd6bdd852a11e481292e4298c0a939157'; //媒体平台取链获得的p参数
    const ASE_KEY = 'd6bdd852a11e481292e4298c0a939157'; //媒体平台取链获得的p参数
    const bm = 'UTF-8';

    //活动商家列表
    public function shoplist($mobile,$searchWord,$lat,$lng,$pagePvId,$sortType,$canSignup,$needEvaluate)
    {
        $api = $this->url.'act/cpsapi/get_list_v3';

        //$mobile = '13785955555';

        $mediaUserid = $this->encrypt($mobile);

        $data = [
            'p'=>$this->p,//推广链接id
            'mediaPvid'=>$this->mediaPvid,//请求标识
            'lat'=>$lat,//
            'lon'=>$lng,//
            'mediaUserid'=>$mediaUserid,//用户标识(用户加密手机号)
            'sortType'=>$sortType,//排序0默认,1距离最近,2佣金降序
            'pagePvId'=>$pagePvId
        ];

        if ($searchWord)$data['searchWord'] = $searchWord;
        $data = json_encode($data,320);

        $res = $this->https_request($api,$data);
        $result = json_decode($res,true);

        if ($result['retStatus']==0){
            foreach ($result['poiList'] as $k=>$v){
                Http::get($v['actionUrl']['impMonitorUrl']);
                $planActivityInfoList = $v['planActivityInfoList'];

                foreach ($planActivityInfoList as $kk=>$vv){
                    if ($canSignup==0&&$vv['inventory']==0){
                        unset($planActivityInfoList[$kk]);
                    }
                    if ($needEvaluate==1&&$vv['planActivityType']==2){
                        unset($planActivityInfoList[$kk]);
                    }
                    if ($needEvaluate==2&&$vv['planActivityType']==1){
                        unset($planActivityInfoList[$kk]);
                    }
                }


                if (count($planActivityInfoList)==0){
                    unset($result['poiList'][$k]);
                } else {
                    $result['poiList'][$k]['planActivityInfoList'] = array_values($planActivityInfoList);
                }

            }
            $result['poiList'] = array_values($result['poiList']);
            return $result;
        } else {
            throw new \Exception($result['message']);
        }
    }

    //活动报名
    public function signup($user_id,$mobile,$poiEventId,$meituanPvId,$lat,$lng,$shop_name,$shop_logo,$wxAppid,$wxPath,$planActivityType)
    {
        $api = $this->url.'act/cpsapi/registerevent';

        //$mobile = '13785955555';

        $mediaUserid = $this->encrypt($mobile);

        $ip = request()->ip();

        $data = [
            'mediaUserId'=>$mediaUserid,//用户标识(用户加密手机号)
            'poiEventId'=>$poiEventId,//商家id
            'p'=>$this->p,//推广链接id
            'meituanPvId'=>$meituanPvId,
            'actualLongitude'=>$lng,//
            'actualLatitude'=>$lat,//
            'clientIp'=>$ip,//客户的ip
            'cashBackMode'=>0,//用户返现方式,0独立返现,1统一返现
            'subsidyRatio'=>10000,//渠道补贴⽐例,
        ];

        $data = json_encode($data,320);

        $res = $this->https_request($api,$data);

        $result = json_decode($res,true);

        if ($result['code']==0){

            $detail = UserOverlordMealOrder::where(['order_no'=>$result['userEventId'],'user_id'=>$user_id,'poiEventId'=>$poiEventId])->find();
            if (!$detail){
                $order_model = new UserOverlordMealOrder();
                $order_data = [
                    'order_no'=>$result['userEventId'],
                    'user_id'=>$user_id,
                    'mobile'=>$mobile,
                    'platform'=>'mt',
                    'shop_name'=>$shop_name,
                    'shop_logo'=>$shop_logo,
                    'ratio'=>$result['ratio']/10000,
                    'maxCommission'=>$result['maxCommission']/100,
                    //'mediaRatio'=>$result['mediaRatio']/10000,
                    //'mediaMaxCommission'=>$result['mediaMaxCommission']/100,
                    'expired_time'=>isset($result['orderLimitExactTime'])?$result['orderLimitExactTime']/1000:0,
                    'poiEventId'=>$poiEventId,
                    'wxAppid'=>$wxAppid,
                    'wxPath'=>$wxPath,
                    'planActivityType'=>$planActivityType
                ];
                $order_model->save($order_data);
            }

            return $result;
        } else {
            throw new \Exception($result['msg']);
        }
    }

    //活动取消
    public function cancel($order_no)
    {
        $api = $this->url.'act/cpsapi/cancelevent';

        $record = UserOverlordMealOrder::get(['order_no'=>$order_no]);
        if ($record){
            $mobile = $record->mobile;
            if ( $record->status == -1){
                throw new \Exception('已取消');
            }
        } else {
            throw new \Exception('报名不存在');
        }

        $mediaUserid = $this->encrypt($mobile);

        $data = [
            'p'=>$this->p,//推广链接id
            'mediaUserId'=>$mediaUserid,//用户标识(用户加密手机号)
            'userEventId'=>$order_no
        ];

        $data = json_encode($data,320);

        $res = $this->https_request($api,$data);
        $result = json_decode($res,true);

        if ($result['code']==0){
            $record->status = -1;
            $record->expire_reason = '失效原因: 已取消报名';
            $record->save();
            return $result['data'];
        } else {
            throw new \Exception($result['msg']);
        }
    }

    public function accountstate()
    {
        $api = $this->url.'act/cpsapi/load_order';

        $data = [
            'p'=>$this->p,//推广链接id
            'startTime'=>1734451140
        ];

        $data = json_encode($data,320);

        $res = $this->https_request($api,$data);
        $result = json_decode($res,true);
        if ($result['code']==0){
            return $result;
        } else {
            throw new \Exception($result['msg']);
        }
    }

    //查询⽤户任务状态
    public function taskstatus($userEventId)
    {
        $api = $this->url.'act/cpsapi/queryeventprogress';

        $record = UserOverlordMealOrder::get(['order_no'=>$userEventId]);
        if ($record){
            $mobile = $record->mobile;
        } else {
            $mobile = '13785955555';
        }

        $mediaUserid = $this->encrypt($mobile);

        $data = [
            'p'=>$this->p,//推广链接id
            'mediaUserId'=>$mediaUserid,//用户标识(用户加密手机号)
            'userEventId'=>$userEventId
        ];

        $data = json_encode($data,320);

        $res = $this->https_request($api,$data);
        $result = json_decode($res,true);


        if ($result['code']==0){
            /*$code = $result['code'];
            switch ($code) {
                case 1:
                    //已过期 失效状态
                    $status = -1;
                    $expire_reason = '失效原因: 超时自动放弃';
                    break;
                case 2:
                    //已取消 失效状态
                    $status = -1;
                    $expire_reason = '失效原因: 已取消报名';
                    break;
                case 3:
                    //已报名 任务进行中，未下单

                    break;
                case 4:
                    //已下单 下单完成

                    break;
                case 5:
                    //已评价 评价完成

                    break;
                case 6:
                    //任务失败 失效状态,中途失败、风控拦截均可能导致失败
                    $status = -1;
                    $expire_reason = '失效原因: 任务失败';
                    break;
                case 100:
                    //任务完成 完成活动任务

                    break;
            }
            $record->status = $status;
            $record->expire_reason = $expire_reason;
            $record->save();*/
            return $result;
        } else {
            throw new \Exception($result['msg']);
        }
    }


    //任务状态反馈回调
    public function taskfeedback($data)
    {
        Log::error('任务状态反馈回调');
        Log::error(json_encode($data,320));
        $code = $data['code'];
        $userEventId = $data['userEventId'];
        $order_id = isset($data['orderId'])?$data['orderId']:0;
        $realCharge = isset($data['realCharge'])?$data['realCharge']:0;
        $timestamp = isset($data['timestamp'])?$data['timestamp']:0;
        $record = UserOverlordMealOrder::get(['order_no'=>$userEventId]);
        if ($record->status==-1){
            throw new \Exception('已失败');
        }

        switch ($code) {
            case 3:
                //已报名 任务进行中，未下单

                break;
            case 4:
                //已下单 下单完成
                $pay_price = $realCharge/100;
                $record->order_id = $order_id;
                $record->pay_price = $pay_price;
                $record->pay_time = $timestamp/1000;
                //$record->totalCommission = bcmul($pay_price,$record->ratio,2);
                $record->save();
                break;
            case 6:
                //任务失败 用户任务失败
                $status = -1;
                if (isset($data['orderId'])){
                    $expire_reason = '失效原因: 订单退款';
                } else {
                    $expire_reason = '失效原因: 超时自动放弃';
                }
                $record->status = $status;
                $record->expire_reason = $expire_reason;
                $record->save();
                break;
            case 7:
                //已返现 平台给用户返现完成后，通知渠道【统一返现终态
                $status = 2;
                $record->status = $status;
                $record->save();
                break;
            case 99:
                //审核中 可疑订单，进行风控审核
                $status = 1;
                $record->status = $status;
                $record->save();
                break;
            case 100:
                //任务完成 完成活动任务【独立返现终态】（用户后续退款，会推送失败状态）
                $record->userCommission = $data['commission']/100*0.75;
                $record->totalCommission = $data['commission']/100;
                //$record->expectedCashbackTime = $data['expectedCashbackTime']/1000;
                $status = 1;
                $record->status = $status;
                $record->complete_time = time();
                $record->save();
                break;
        }

        //if ($record->status!=2){
        $consume_log_info = UserConsumeLog::get([ 'user_id'=>$record->user_id, 'order_no'=>$record->order_id,'consume_type'=>4,'cps_type'=>9]);

        if ($code==100){
            $total_commission = $record->totalCommission;
            //$total_commission = $record->userCommission;
            $commission = $record->userCommission;
            if (!$consume_log_info){
                $consume_log_model = new UserConsumeLog();
                $consume_log_data = [
                    'user_id'=>$record->user_id,
                    'title'=>$record->shop_name,
                    'shop_id'=>0,
                    'shop_name'=>$record->shop_name,
                    'image'=>$record->shop_logo,
                    'order_no'=>$record->order_id,
                    'pay_time'=>$record->pay_time,
                    'pay_price'=>$record->pay_price,
                    'consume_type'=>4,
                    'cps_type'=>9,
                    'goods_id'=>0,
                    'commission'=>$commission,
                    'total_commission'=>$total_commission,
                    'order_status_name'=>'已付款'
                ];
                $consume_log_model->save($consume_log_data);
                $operable_commission = bcsub($total_commission,$commission,2);

                UserConsumeLog::dineDashConsumeCalculate($record->user_id,$operable_commission,$consume_log_model->consume_id);
                UserConsumeLog::dineDashShopConsumeCalculate($record->user_id,$operable_commission,$consume_log_model->consume_id);

            }
        } elseif ($code==6){
            $consume_log_info->commission = 0;
            $consume_log_info->order_status_name = '退款成功';
            $consume_log_info->is_refund = 1;
            $consume_log_info->save();
            ExtendConsume::update(['commission'=>0],['consume_log_id'=>$consume_log_info->consume_id]);
            ExtendConsumeShop::update(['commission'=>0],['consume_log_id'=>$consume_log_info->consume_id]);
        } elseif ($code==7){
            //UserConsumeLog::sendCommission($consume_log_info->order_no);
        }
        //}

        return true;
    }


    public function encrypt($cleartext) {
        $limitLength = 16;
        $VIPARA_LL = substr(self::VIPARA, 0, $limitLength);//限制长度为16个字符
        $ASE_KEY_LL = substr(self::ASE_KEY, 0, $limitLength);//限制长度为16个字符
        $encryptedData = openssl_encrypt($cleartext, 'AES-128-CBC', $ASE_KEY_LL, OPENSSL_RAW_DATA, $VIPARA_LL);
        $base64Data = base64_encode($encryptedData);
        return $base64Data;
    }

    public function https_request($url,$data = null){
        // 初始化cURL会话
        $ch = curl_init($url);

        // 设置cURL选项
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data))
        );

        $result = curl_exec($ch);

        curl_close($ch);

        return $result;
    }
}